/*
 * simpleUART.c
 *
 *  Created on: 26.2.2012
 *      Author: lukas
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include "simpleUART.h"

/*
 * Initializes UART
 * Parity Odd, Stop bit 1
 * Baudrate comes from clock and baudRate - consult manual
 * set baudRate to 25 to get 19200 baud on 8MHz
 */
void UARTInit(uint16_t baudRate) {
	cli();
	UBRRL = baudRate;
	UBRRH = (baudRate >> 8);
	UCSRA = 0x00;
	UCSRB = (1 << RXEN) | (1 << TXEN);
	UCSRC = (1 << URSEL) | (1 << UCSZ0) | (1 << UCSZ1) | (1 << UPM0) | (1 << UPM1);
	sei();
}

/*
 * Blocking reading of one char from the UART interface
 * UART must be initialize before using this method
 */
char UARTReadChar() {
	while (!(UCSRA & (1 << RXC))) {
		// Do nothing
	}
	return UDR;
}

/*
 * Blocking writing of one char to the UART
 * (will wait until it is possible to send the value)
 * UART must be initialize before using this method
 */
void UARTWriteChar(char data) {
	while (!(UCSRA & (1 << UDRE))) {
	  // Do nothing
	}

	UDR = data;
}
